package com.example.springbootdemo.elasticsearch;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootdemo.returns.JsonReturn;
import com.example.springbootdemo.statics.JsonKeyStatic;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("article")
public class ArticleController {

    @Autowired
    private ArticleRepository articleRepository;

    @GetMapping("save")
    public Object save() {
        for (long id = 1; id < 10; id++) {
            Article article = new Article();
            article.setId(id);
            article.setPv(100 + (int) id);
            article.setContent("springboot整合elasticsearch");
            article.setTitle("title" + id);
            article.setSummary("搜索框架整合");

            articleRepository.save(article);
        }
        return new JsonReturn().SUCCESS_JSON;
    }

    @GetMapping("search")
    public Object search(String title) {
//        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery(); //搜索全部文档
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", title);
        Iterable<Article> list = articleRepository.search(queryBuilder);
        JSONObject SUCCESS_JSON = new JsonReturn().SUCCESS_JSON;
        SUCCESS_JSON.put(JsonKeyStatic.DATA, list);
        return SUCCESS_JSON;
    }

}
